package org.example.rabbitmq.simple;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @author taritari
 * @date 2023-11-22 15:01
 * @description
 */
public class Consumer {
    public static void main(String[] args) {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("****");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setVirtualHost("my_vhost");
        Connection connection = null;
        Channel channel = null;
        try {
            connection = connectionFactory.newConnection("生产者");
            channel = connection.createChannel();
            channel.basicConsume("queue1", true, new DeliverCallback() {
                @Override
                public void handle(String s, Delivery delivery) throws IOException {
                    System.out.println("收到消息是:"+new String(delivery.getBody(),"UTF-8"));
                }
            }, new CancelCallback() {
                @Override
                public void handle(String s) throws IOException {
                    System.out.println("接收失败了");
                }
            });


            System.out.println("开始接收消息");
            System.in.read();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (channel != null && channel.isOpen()){
                try {
                    connection.close();
                }catch (Exception exception){
                    exception.printStackTrace();
                }
            }

            if (connection != null && connection.isOpen()){
                try {
                    connection.close();
                }catch (Exception exception){
                    exception.printStackTrace();
                }
            }
        }
    }
}
